package net.zigin.nhi.could.waste.util;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import net.zigin.nhi.could.waste.config.QiniuConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Random;

@Component
public class OSSQiniuUtil {

    @Autowired
    private QiniuConfiguration config;

    public String uploadFile (MultipartFile file) throws RuntimeException{
        if (file == null || file.getSize() <= 0) {
            throw new RuntimeException("file不能为空");
        }
        if (file.getSize() > 50 * 1024 * 1024) {
            throw new RuntimeException("上传图片大小不能超过50M！");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            String fileName = this.uploadFile2OSS(inputStream, name);
            return config.getEndPoint() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("图片上传失败");
        }
    }

    public String uploadFile2OSS(InputStream inputStream, String name) {
        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        String upToken = auth.uploadToken(config.getBucketName());
        try {
            Response response = uploadManager.put(inputStream, name, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (Exception ex) {
            throw new RuntimeException("图片上传失败");
        }
    }
}
